<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="健身房名称" prop="gymname">
        <el-input v-model="form.gymname" placeholder="请输入健身房名称" />
      </el-form-item>

      <el-form-item label="管理员姓名" prop="gym_manger">
        <el-input v-model="form.gym_manger" placeholder="请输入管理员姓名" />
      </el-form-item>

      <el-form-item label="联系电话" prop="gym_mobile">
        <el-input v-model="form.gym_mobile" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="所在地区" required>
        <el-cascader
          v-model="regionData"
          :options="regionOptions"
          placeholder="请选择省/市/区"
          @change="handleRegionChange"
        />
      </el-form-item>

      <el-form-item label="位置选择" prop="gym_point">
        <div class="map-container" style="height: 400px">
          <el-amap
            ref="map"
            :center="mapCenter"
            :zoom="12"
            :events="mapEvents"
          >
            <el-amap-marker
              v-if="markerPosition"
               :position="markerPosition"
               :icon="markerIcon"
               :draggable="true"
            />
          </el-amap>
        </div>
      </el-form-item>

      <el-form-item label="健身房简介" prop="gym_slogan">
        <el-input
          v-model="form.gym_slogan"
          type="textarea"
          placeholder="请输入健身房简介"
        />
      </el-form-item>

      <el-form-item label="健身房图片" prop="gym_imgs">
        <el-upload
          ref="upload"
          :action="uploadUrl"
          :limit="5"
          :on-success="handleUploadSuccess"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          multiple
         :headers="headers"
          list-type="picture-card"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import { addGym } from "@/api/gym";
import { getToken } from '@/utils/auth'
export default {
  name: "AddGym",
  data() {
    return {
       headers: {
            Authorization: 'Bearer ' + getToken()
          },
       mapEvents: {
        click: (e) => {
          const lng = e.lnglat.getLng()
          const lat = e.lnglat.getLat()
          this.form.gym_point = [lng, lat]
            this.markerPosition = [lng, lat] // 添加这行
         console.log( this.markerPosition,"点的位置，---")
          this.$message.success(`已选择位置：经度 ${lng}, 纬度 ${lat}`)
        }
      },
      markerPosition:null,
       markerIcon: {
        type: 'image',
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 使用高德地图提供的红色标记图标
        size: [20, 32],  // 图标大小
        anchor: 'bottom-center' // 锚点位置
      },
      form: {
        gymname: "",
        gym_manger: "",
        gym_mobile: "",
        gymid: "",
        gym_province: "",
        gym_city: "",
        gym_area: "",
        gym_slogan: "",
        gym_imgs: [],
        gym_point: [],
      },
      rules: {
        gymname: [
          { required: true, message: "请输入健身房名称", trigger: "blur" },
        ],
        gym_manger: [
          { required: true, message: "请输入管理员姓名", trigger: "blur" },
        ],
        gym_mobile: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        gym_slogan: [
          { required: true, message: "请输入健身房简介", trigger: "blur" },
        ],
        gym_imgs: [
          { required: true, message: "请上传健身房图片", trigger: "change" },
        ],
      },
      regionData: [],
      regionOptions: [], // 需要从后端获取省市区数据
      mapCenter: [116.397428, 39.90923],
      uploadUrl: "/dev-api/gym/uploadImage", // 上传接口地址
    };
  },
  created() {
    this.getRegionData();
  },
  methods: {
    // 获取省市区数据
    getRegionData() {
      // 实现获取省市区数据的逻辑
    },

    // 地区选择改变
    handleRegionChange(value) {
      this.form.gym_province = value[0];
      this.form.gym_city = value[1];
      this.form.gym_area = value[2];
    },

    // 地图点击事件
    handleMapClick(e) {
      this.form.gym_point = [e.lnglat.lng, e.lnglat.lat];
        // 可以添加提示信息
        console.log(this.form.gym_point,"----------")
      this.$message.success(`已选择位置：经度 ${e.lnglat.lng}, 纬度 ${e.lnglat.lat}`);
    },

    // 上传成功回调
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.form.gym_imgs.push(response.data);
      } else {
        this.$message.error("上传失败");
      }
    },

    // 移除图片
    handleRemove(file) {
      const index = this.form.gym_imgs.indexOf(file.response.data);
      if (index !== -1) {
        this.form.gym_imgs.splice(index, 1);
      }
    },

    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // addGym(this.form).then((response) => {
          //   if (response.code === 200) {
          //     this.$message.success("添加成功");
          //     this.$router.push("/gym/list");
          //   } else {
          //     this.$message.error(response.msg);
          //   }
          // });
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.form.gym_imgs = [];
      this.form.gym_point = [];
      this.regionData = [];
      this.markerPosition = []; // 添加这行
    },
  },
};
</script>

<style scoped>
.map-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
